#!/bin/bash

# 生产环境部署脚本
# 使用方法: ./deploy-prod.sh [版本号]

set -e  # 遇到错误时退出

VERSION=${1:-"latest"}
PROJECT_NAME="learning-platform"
DEPLOY_DIR="/opt/${PROJECT_NAME}"
BACKUP_DIR="/opt/${PROJECT_NAME}-backups"
LOG_FILE="/var/log/${PROJECT_NAME}-deploy.log"

echo "======================================"
echo "在线学习平台 - 生产环境部署脚本"
echo "======================================"
echo "版本: $VERSION"
echo "部署目录: $DEPLOY_DIR"
echo "备份目录: $BACKUP_DIR"
echo "======================================"

# 检查是否为root用户
if [ "$EUID" -ne 0 ]; then
    echo "[错误] 请使用root权限运行此脚本"
    exit 1
fi

# 记录部署日志
exec > >(tee -a $LOG_FILE)
exec 2>&1

echo "[$(date)] 开始部署 $PROJECT_NAME v$VERSION"

# 1. 创建必要目录
echo "[步骤1] 创建目录结构..."
mkdir -p $DEPLOY_DIR
mkdir -p $BACKUP_DIR
mkdir -p /var/log/$PROJECT_NAME

# 2. 停止现有服务
echo "[步骤2] 停止现有服务..."
systemctl stop learning-backend || true
systemctl stop learning-ai || true
systemctl stop nginx || true

# 3. 备份现有部署
if [ -d "$DEPLOY_DIR/current" ]; then
    echo "[步骤3] 备份现有部署..."
    BACKUP_NAME="${PROJECT_NAME}-$(date +%Y%m%d_%H%M%S)"
    mv "$DEPLOY_DIR/current" "$BACKUP_DIR/$BACKUP_NAME"
    echo "备份保存至: $BACKUP_DIR/$BACKUP_NAME"
fi

# 4. 克隆/更新代码
echo "[步骤4] 获取最新代码..."
if [ ! -d "$DEPLOY_DIR/repo" ]; then
    git clone https://github.com/your-username/learning-platform.git "$DEPLOY_DIR/repo"
else
    cd "$DEPLOY_DIR/repo"
    git fetch origin
    git reset --hard HEAD
fi

cd "$DEPLOY_DIR/repo"
if [ "$VERSION" != "latest" ]; then
    git checkout "v$VERSION"
else
    git checkout main
fi

# 5. 创建当前部署目录
echo "[步骤5] 准备部署文件..."
cp -r "$DEPLOY_DIR/repo" "$DEPLOY_DIR/current"
cd "$DEPLOY_DIR/current"

# 6. 构建后端
echo "[步骤6] 构建后端应用..."
cd backend
./mvnw clean package -DskipTests -Pprod
mv target/*.jar ../learning-backend.jar
cd ..

# 7. 构建前端
echo "[步骤7] 构建前端应用..."
cd frontend
npm ci
npm run build
cd ..

# 8. 配置环境变量
echo "[步骤8] 配置环境变量..."
cat > /etc/environment << EOF
# Learning Platform Environment Variables
DB_HOST=${DB_HOST:-localhost}
DB_PORT=${DB_PORT:-3306}
DB_NAME=${DB_NAME:-learning}
DB_USERNAME=${DB_USERNAME:-learning}
DB_PASSWORD=${DB_PASSWORD}
JWT_SECRET=${JWT_SECRET}
UPLOAD_DIR=${UPLOAD_DIR:-/opt/learning-platform/uploads}
SPRING_PROFILES_ACTIVE=prod
EOF

# 9. 设置文件权限
echo "[步骤9] 设置文件权限..."
chown -R learning:learning $DEPLOY_DIR
chmod +x learning-backend.jar
mkdir -p /opt/learning-platform/uploads
chown -R learning:learning /opt/learning-platform/uploads

# 10. 配置systemd服务
echo "[步骤10] 配置系统服务..."

# 后端服务
cat > /etc/systemd/system/learning-backend.service << EOF
[Unit]
Description=Learning Platform Backend
After=mysql.service

[Service]
Type=simple
User=learning
WorkingDirectory=$DEPLOY_DIR/current
ExecStart=/usr/bin/java -jar -Xms512m -Xmx2g -Dspring.profiles.active=prod learning-backend.jar
Restart=always
RestartSec=10

Environment=DB_HOST=${DB_HOST:-localhost}
Environment=DB_PORT=${DB_PORT:-3306}
Environment=DB_NAME=${DB_NAME:-learning}
Environment=DB_USERNAME=${DB_USERNAME:-learning}
Environment=DB_PASSWORD=${DB_PASSWORD}
Environment=JWT_SECRET=${JWT_SECRET}
Environment=UPLOAD_DIR=/opt/learning-platform/uploads

[Install]
WantedBy=multi-user.target
EOF

# AI服务
cat > /etc/systemd/system/learning-ai.service << EOF
[Unit]
Description=Learning Platform AI Service
After=network.target

[Service]
Type=simple
User=learning
WorkingDirectory=$DEPLOY_DIR/current/ai
Environment=PATH=$DEPLOY_DIR/current/ai/venv/bin
ExecStart=$DEPLOY_DIR/current/ai/venv/bin/python main.py
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# 11. 配置Nginx
echo "[步骤11] 配置Nginx..."
cat > /etc/nginx/sites-available/learning-platform << EOF
server {
    listen 80;
    server_name ${DOMAIN:-localhost};
    root $DEPLOY_DIR/current/frontend/dist;
    index index.html;

    # 前端路由
    location / {
        try_files \$uri \$uri/ /index.html;
    }

    # API代理
    location /api/ {
        proxy_pass http://localhost:8080;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # AI服务代理
    location /ai/ {
        proxy_pass http://localhost:8000;
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # 静态文件缓存
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # 文件上传大小限制
    client_max_body_size 50M;
}
EOF

ln -sf /etc/nginx/sites-available/learning-platform /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default

# 12. 安装AI依赖
echo "[步骤12] 安装AI依赖..."
cd ai
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
cd ..

# 13. 重新加载systemd并启动服务
echo "[步骤13] 启动服务..."
systemctl daemon-reload
systemctl enable learning-backend
systemctl enable learning-ai
systemctl enable nginx

systemctl start learning-backend
systemctl start learning-ai
systemctl start nginx

# 14. 健康检查
echo "[步骤14] 健康检查..."
sleep 10

# 检查后端
if curl -f http://localhost:8080/api/v1/health > /dev/null 2>&1; then
    echo "✓ 后端服务启动成功"
else
    echo "✗ 后端服务启动失败"
    systemctl status learning-backend
fi

# 检查AI服务
if curl -f http://localhost:8000/health > /dev/null 2>&1; then
    echo "✓ AI服务启动成功"
else
    echo "✗ AI服务启动失败"
    systemctl status learning-ai
fi

# 检查Nginx
if curl -f http://localhost/ > /dev/null 2>&1; then
    echo "✓ 前端服务启动成功"
else
    echo "✗ 前端服务启动失败"
    systemctl status nginx
fi

echo "======================================"
echo "部署完成!"
echo "======================================"
echo "服务状态:"
echo "- 后端: http://localhost:8080/api/v1/health"
echo "- AI服务: http://localhost:8000/health"
echo "- 前端: http://localhost/"
echo ""
echo "日志查看:"
echo "- 后端: journalctl -u learning-backend -f"
echo "- AI服务: journalctl -u learning-ai -f"
echo "- Nginx: tail -f /var/log/nginx/error.log"
echo "======================================"
echo "[$(date)] 部署完成"





